AddCSLuaFile("shared.lua")
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("scale.lua")
AddCSLuaFile("surface_new.lua")

include("shared.lua")

if GetConVarString("sv_scriptenforcer") == "0" then 
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
print("!!!Warning Scriptenforcer is off and could give Cheaters an advantage!!!")
print("!!!Warning!! Add sv_scriptenforcer 1 to the server.cfg File !!Warning!!!")
print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!")
end

local bAllowWeapons = CreateConVar("b_AllowWeapons","1",{FCVAR_REPLICATED,FCVAR_NOTIFY})

SoccerJam.Name = "SoccerJam"
SoccerJam.RoundStart = false 
SoccerJam.Score1 = false
SoccerJam.Score2 = false
SoccerJam.Team1 = false
SoccerJam.Team2 = false
SoccerJam.BallTime = 0
SoccerJam.Ball = 0
SoccerJam.Blue = 0
SoccerJam.Red = 0
SoccerJam.Score = 0
SoccerJam.GoalToReach = 20

SoccerJam.BallSpawn = {
	{
	Vec = Vector(6143, 3329, 1024), 
	Map = "sj_soccer",
	},
}

local ValidExtensions = {
    ".wav",
    ".ogg",
    ".mp3",
    ".txt",
    ".mdl",
    ".vtf",
    ".vmt",
}

//DownloadFiles("models/weapons/smod_kick",".mdl")

function DownloadFiles(folder,ext,ext2)
	folder = tostring(folder)
	ext = tostring(ext)
	ext2 = tostring(ext2)
	if ext && !table.HasValue(ValidExtensions,ext) then print("Not a Valid Extention: "..tostring(ext)) return end
	for k,v in pairs(file.Find(folder.."/*",true)) do 
		if string.find(v,ext) || string.find(v,ext2) then
			if (v):lower():find(".mp3") || (v):lower():find(".wav") || (v):lower():find(".ogg") then
					local RP = RecipientFilter() 
					umsg.Start("PrecSound", RP)
					umsg.String(folder.."/"..v)
					umsg.End()
					resource.AddFile(folder.."/"..v)
				elseif (v):lower():find(".mdl") then
					local RP = RecipientFilter() 
					umsg.Start("PrecModel", RP)
					umsg.String(folder.."/"..v)
					umsg.End()
					resource.AddFile(folder.."/"..v)
				elseif (v):lower():find(".vtf") || (v):lower():find(".vmt") || (v):lower():find(".txt") then
					resource.AddFile(folder.."/"..v)
			end
		end
	end
end

DownloadFiles("sound/soccer",".wav",".mp3")
DownloadFiles("sound/soccer/achivement",".wav",".mp3")
DownloadFiles("sound/soccer/leeroy",".wav",".mp3")
DownloadFiles("sound/soccer/ravebreak",".wav",".mp3")

resource.AddFile("models/weapons/v_kick.mdl")
//
//*************************
//Example Use - For Admins Only
//RunCommand "game.ConsoleCommand('b_AllowWeapons 1\n')"
//*************************
//
function RunCommand(ply,cmd,args) 
	if !args[1] then ply:ChatPrint([[Example Use RunCommand "game.ConsoleCommand('b_AllowWeapons 1\n')"]]) end
	if ply:IsAdmin() then
		RunString(tostring(args[1])) 
		local RP = RecipientFilter()
		RP:AddAllPlayers()
		umsg.Start("RunCommand", RP)
		umsg.Entity(ply)
		umsg.String(tostring(args[1]))
		umsg.End()
	end 
end 
concommand.Add("RunCommand",RunCommand)
//

function GM:GetGameDescription()
	return SoccerJam.Name
end

function _R.Player:SetMoney(money)
	money = tonumber(money)
	return self:SetNWInt("cash",money or 0)
end

function _R.Player:AddMoney(money)
	money = tonumber(money)
	return self:SetNWInt("cash", self:GetNWInt("cash") + money or 0)
end

function GM:Tick()
	if #team.GetPlayers(1) > 0 and #team.GetPlayers(2) > 0 then
		SoccerJam.RoundStart = true
	elseif #team.GetPlayers(1) < 1 and #team.GetPlayers(2) > 0 then
		for k,v in pairs(ents.GetAll()) do
			if (v:GetClass() == "prop_physics" && v:GetModel() == "models/props_phx/misc/soccerball.mdl") then
				v:Remove()
			end
		end
		SoccerJam.RoundStart = false
		SoccerJam.Ball = 0
	elseif #team.GetPlayers(1) > 0 and #team.GetPlayers(2) < 1 then
		for k,v in pairs(ents.GetAll()) do
			if (v:GetClass() == "prop_physics" && v:GetModel() == "models/props_phx/misc/soccerball.mdl") then
				v:Remove()
			end
		end
		SoccerJam.RoundStart = false
		SoccerJam.Ball = 0
	end
	if CurTime() >= SoccerJam.BallTime then
	if SoccerJam.RoundStart == true and SoccerJam.Ball == 0 then
		for k,v in pairs(SoccerJam.BallSpawn) do
			if string.find(game.GetMap(),v.Map) then
				scball = ents.Create("soccerball")
				scball:SetPos(Vector(v.Vec[1],v.Vec[2],v.Vec[3]))
				scball:Spawn()
				scball:Activate()
				SoccerJam.Ball = 1
			end
		end
	end
		SoccerJam.BallTime = CurTime() + 10
	end
	
	if game.GetMap() == "sj_soccer" then
		for k,v in pairs(ents.FindInBox(Vector(6020.0640, 4716.5049, 1061.8459), Vector(6266.7075, 4774.2065, 1005.4476)  ) ) do 
			if v:GetClass() == "soccerball" then
				v:Remove()
				SoccerJam.Score1 = true
				if SoccerJam.Score1 == true then
					scball:SetParent( nil )
					scball:SetMoveType( MOVETYPE_VPHYSICS )
					scball:SetSolid( SOLID_VPHYSICS )
					SoccerJam.Team1 = true
					Goaling()
				end
			end
		end
		
		for k,v in pairs(ents.FindInBox( Vector(6267.4863, 1938.3090, 1093.0980), Vector(6021.5146, 1884.4462, 999.6468) ) ) do 
			if v:GetClass() == "soccerball" then
				v:Remove()
				SoccerJam.Score2 = true
				if SoccerJam.Score2 == true then
					scball:SetParent( nil )
					scball:SetMoveType( MOVETYPE_VPHYSICS )
					scball:SetSolid( SOLID_VPHYSICS )
					SoccerJam.Team2 = true
					Goaling()
				end
			end
		end
	end


end

local WinSounds = {"soccer/amaze.wav","soccer/laugh.wav","soccer/perfect.wav","soccer/witch.wav"}
function Goaling()
	if SoccerJam.GoalToReach == SoccerJam.Red then
	game.ConsoleCommand("changelevel sj_soccer\n")
	elseif SoccerJam.GoalToReach == SoccerJam.Blue then
	game.ConsoleCommand("changelevel sj_soccer\n")
	end
	
	if SoccerJam.Team1 == true then
	SoccerJam.Team1 = false
	SoccerJam.Score1 = false
	SoccerJam.RoundStart = true
	SoccerJam.Ball = 0
	if CurTime() >= SoccerJam.Score then
	SoccerJam.Blue = SoccerJam.Blue + 1
	local RP = RecipientFilter()
	RP:AddAllPlayers()
	umsg.Start("BlueScore",RP)
	umsg.Short(SoccerJam.Blue)
	umsg.End()
	SoccerJam.Score = CurTime() + 1
	end
	for _,ply in pairs(player.GetAll()) do
	local WinSounda = CreateSound(ply, Sound("soccer/distress.wav") )
	local WinNSounda = CreateSound(ply, Sound(WinSounds[math.random(1,#WinSounds)]))
	WinSounda:Play()
	WinNSounda:Play()
	timer.Simple(6, function() WinSounda:Stop() WinNSounda:Play() end)
	end
	elseif SoccerJam.Team2 == true then
	SoccerJam.Team2 = false
	SoccerJam.Score2 = false
	SoccerJam.RoundStart = true
	SoccerJam.Ball = 0
	if CurTime() >= SoccerJam.Score then
	SoccerJam.Red = SoccerJam.Red + 1
	local RP = RecipientFilter()
	RP:AddAllPlayers()
	umsg.Start("RedScore",RP)
	umsg.Short(SoccerJam.Red)
	umsg.End()
	SoccerJam.Score = CurTime() + 1
	end
	for _,ply in pairs(player.GetAll()) do
	local WinSoundb = CreateSound(ply, Sound("soccer/distress.wav") )
	local WinNSoundb = CreateSound(ply, Sound(WinSounds[math.random(1,#WinSounds)]))
	WinSoundb:Play()
	WinNSoundb:Play()
	timer.Simple(6, function() WinSoundb:Stop() WinNSoundb:Stop() end)
	end
	end
	
end

function FindByClassRemove(str)
	for k,v in pairs(ents.GetAll()) do
		if ValidEntity(v) then
			if string.find(v:GetClass(),str) then
				v:Remove()
			end
		end
	end
end

function GM:InitPostEntity()
	FindByClassRemove("func_physbox") //Soccer Ball
	FindByClassRemove("trigger_hurt") // Kills players
	FindByClassRemove("point_servercommand") // Executes stuff in the server
	FindByClassRemove("ambient_generic") // Sounds
end

function GM:PlayerInitialSpawn(ply)
	self.BaseClass:PlayerInitialSpawn(ply)
	ply:SetTeam(team.BestAutoJoinTeam())
	umsg.Start("GoalToReach", ply)
	umsg.String(SoccerJam.GoalToReach)
	umsg.End()
end

function GM:PlayerSpawn( ply )
	
	if ply:Team() == 1 then
	
		ply:SetPData( "model", "models/player/urban.mdl" )
		ply:SetModel( "models/player/urban.mdl" )
		
	elseif ply:Team() == 2 then
	
		ply:SetPData( "model", "models/player/alyx.mdl" )
		ply:SetModel( "models/player/alyx.mdl" )

	end		
	
	ply:SetModel( ply:GetPData( "model" ) )
	
	if ply:Team() == 1 then
	if bAllowWeapons:GetBool() then
	ply:Give( "weapon_crowbar" )
	end
	elseif ply:Team() == 2 then
	if bAllowWeapons:GetBool() then
	ply:Give( "weapon_crowbar" )
	end
	end
	
end

function GM:PlayerDeath(ply)
	ply:Spawn()
end

function GM:PlayerLoadout( ply )
 
    if ply:Team() == 1 then
		ply:Spawn()
    elseif ply:Team() == 2 then
		ply:Spawn()
    end 
	
end

function GM:PlayerSelectSpawn( ply )
	if string.find(game.GetMap(),"sj_") then
		if ply:Team() == 1 then

			local Blue = ents.FindByClass( "info_player_counterterrorist" )
			return Blue[math.random(#Blue)]
		
		elseif ply:Team() == 2 then

			local Red = ents.FindByClass( "info_player_terrorist" )
			return Red[math.random(#Red)]
			
		end
	end
end